<template>
  <div class="editor-header">
    <div class="left">
      <div class="handler-item icon" @click="goback()">
        <i class="appIcon-iconfont appIcon-zhuye"></i>
      </div>
      <div class="handler-item">
        <input type="text" class="input-title" maxlength="10" v-model="title" />
      </div>
      <!-- <div class="handler-item" @click="saveDoc()">
        <i class="appIcon-iconfont appIcon-baocun"></i>
      </div> -->
      <div class="editor_top_line"></div>
      <Tooltip :mouseLeaveDelay="0" :mouseEnterDelay="0.5" title="撤销">
        <i v-if="handleElementOtherIdList.length < 2" class="handler-item icon appIcon-iconfont appIcon-chexiaofanhuichehuishangyibu"
          :class="{ disable: !canUndo }" @click="undo()"></i>
      </Tooltip>
      <Tooltip :mouseLeaveDelay="0" :mouseEnterDelay="0.5" title="恢复">
        <i v-if="handleElementOtherIdList.length < 2" class="handler-item icon appIcon-iconfont appIcon-xiayibu1"
          :class="{ disable: !canRedo }" @click="redo()"></i>
      </Tooltip>
      <!-- <Tooltip :mouseLeaveDelay="0" :mouseEnterDelay="0.5" title="添加自定义组件">
        <i class="handler-item appIcon-iconfont icon-chuangjianzujian" :class="{ 'disable': !groupVisible }"
          @click="addcustom()"></i>
      </Tooltip> -->
    </div>
    <div class="center" v-if="EditorType == 1">
      <a-popover :visible="alignmentVisible" placement="bottomRight" trigger="hover"
        overlayClassName="editor_topicon_popover">
        <template #content v-if="handleElementId && activeElementIdList.length == 1">
          <p @click="alignElementToCanvas('left')">
            <i class="appIcon-iconfont appIcon-zuoduiqi1"></i><span>左对齐</span>
          </p>
          <p @click="alignElementToCanvas('horizontal')">
            <i class="appIcon-iconfont appIcon-zhongbuduiqi1"></i><span>水平居中</span>
          </p>
          <p @click="alignElementToCanvas('right')">
            <i class="appIcon-iconfont appIcon-youduiqi1"></i><span>右对齐</span>
          </p>
          <p @click="alignElementToCanvas('top')">
            <i class="appIcon-iconfont appIcon-zuoduiqi2"></i><span>顶对齐</span>
          </p>
          <p @click="alignElementToCanvas('vertical')">
            <i class="appIcon-iconfont appIcon-zhongbuduiqi"></i><span>垂直居中</span>
          </p>
          <p @click="alignElementToCanvas('bottom')">
            <i class="appIcon-iconfont appIcon-youduiqi2"></i><span>底对齐</span>
          </p>
          <div v-if="displayItemCount > 2">
            <p @click="uniformHorizontalDisplay()">
              <i class="appIcon-iconfont appIcon-shuipingduiqi1"></i><span>水平等间距</span>
            </p>
            <p @click="uniformVerticalDisplay()">
              <i class="appIcon-iconfont appIcon-shuipingduiqi"></i><span>垂直等间距</span>
            </p>
          </div>
        </template>
        <div class="icon_zuhe handler-item c_bbbdc4" :class="{
          cursornodrop: !handleElementId && activeElementIdList.length !== 1,
        }" @click="alignmentVisibleFn">
          <i class="appIcon-iconfont appIcon-zhedie2 fz16"></i>
          <i class="appIcon-iconfont appIcon-xiala"></i>
        </div>
      </a-popover>
      <a-popover :visible="layerVisible" placement="bottomLeft" overlayClassName="editor_topicon_popover">
        <template #content v-if="handleElementId && activeElementIdList.length == 1">
          <p @click="orderElement(handleElement, 'top')">
            <i class="appIcon-iconfont appIcon-zhiding1"></i><span>置顶</span>
          </p>
          <p @click="orderElement(handleElement, 'bottom')">
            <i class="appIcon-iconfont appIcon-zhiding"></i><span>置底</span>
          </p>
          <p @click="orderElement(handleElement, 'up')">
            <i class="appIcon-iconfont appIcon-ziyuan1"></i><span>上移一层</span>
          </p>
          <p @click="orderElement(handleElement, 'down')">
            <i class="appIcon-iconfont appIcon-ziyuan2"></i><span>下移一层</span>
          </p>
        </template>
        <div class="icon_zuhe handler-item c_bbbdc4" :class="{
          cursornodrop: !handleElementId && activeElementIdList.length !== 1,
        }" @click="layerVisibleFn">
          <i class="appIcon-iconfont appIcon-fuzhi4 fz16"></i>
          <i class="appIcon-iconfont appIcon-xiala"></i>
        </div>
      </a-popover>
      <div class="editor_top_line"></div>
      <Tooltip class="handler-item" v-if="activeElementIdList.length > 1" :mouseLeaveDelay="0" :mouseEnterDelay="0.5"
        :title="canCombine ? '组合' : '取消组合'">
        <i class="appIcon-iconfont appIcon-zuhe c_bbbdc4 fz16" v-if="!canCombine" @click="uncombineElements()"></i>
        <IconUngroup style="margin-right: 3px" @click="combineElements()" v-else />
      </Tooltip>
      <Tooltip class="handler-item" :mouseLeaveDelay="0" :mouseEnterDelay="0.5" title="复制">
        <i class="appIcon-iconfont appIcon-quxiaozuhe c_bbbdc4 fz16" @click="copyElement"></i>
      </Tooltip>
      <div class="editor_top_line"></div>

      <Tooltip class="handler-item" :mouseLeaveDelay="0" :mouseEnterDelay="0.5" title="左右翻转">
        <i class="appIcon-iconfont appIcon-zuoyoufanzhuan_huaban1 c_bbbdc4 fz16"
          :class="{ cursornodrop: handleElement?.type != 'image' }" @click="updateFlip({ flipH: !flipH })"></i>
      </Tooltip>
      <Tooltip class="handler-item" :mouseLeaveDelay="0" :mouseEnterDelay="0.5" title="垂直翻转">
        <i class="appIcon-iconfont appIcon-zuoyoufanzhuan_huaban2 c_bbbdc4 fz16"
          :class="{ cursornodrop: handleElement?.type != 'image' }" @click="updateFlip({ flipV: !flipV })"></i>
      </Tooltip>
      <div class="editor_top_line"></div>
      <Tooltip class="handler-item" :mouseLeaveDelay="0" :mouseEnterDelay="0.5" title="眼睛">
        <i v-if="!handleElement?.hide" class="appIcon-iconfont appIcon-yanjing c_bbbdc4" style="font-size: 17px"
          @click="hideElement(true)"></i>
        <i v-else class="appIcon-iconfont appIcon-tuceng-yincang c_bbbdc4" style="font-size: 17px; opacity: 0.5"
          @click="hideElement(false)"></i>
      </Tooltip>
      <Tooltip class="handler-item" :mouseLeaveDelay="0" :mouseEnterDelay="0.5" title="锁">
        <i v-if="!handleElement?.lock && handleElement?.lock != undefined"
          class="appIcon-iconfont appIcon-24gf-unlock3 c_bbbdc4 fz16" @click="lockElement"></i>
        <i v-else class="appIcon-iconfont appIcon-suo c_bbbdc4 fz16" @click="unlockElement"></i>
      </Tooltip>
      <div class="editor_top_line"></div>
      <!-- <a-switch v-model:checked="checked" size="small" /> -->
      <!-- <Tooltip class="handler-item" :mouseLeaveDelay="0" :mouseEnterDelay="0.5" title="按钮">
        <i class="appIcon-iconfont appIcon-anniu_kaiqi c_bbbdc4"></i>
      </Tooltip> -->
    </div>

    <!-- <div class="right">
      <div class="menu-item handler-item" @click="fare()">
        <i class="appIcon-iconfont appIcon-fenxiangmoren"></i>
      </div>
      <div class="menu-item handler-item">

        <a-popover placement="bottom" trigger="hover" overlayClassName="downloadAs">
          <template #content>
            <div class="downloadFlex">
              <dd @click="autoplay">自动播放</dd>
              <dd @click="enterScreeningFromStart()">手动播放</dd>
            </div>
          </template>
          <i class="appIcon-iconfont appIcon-yulanmoren"></i>
        </a-popover>
      </div>
      <div class="menu-item">

        <a-popover placement="bottom" trigger="hover" overlayClassName="downloadAs">
          <template #content>
            <div class="downloadFlex">
              <dd @click="exportPPTX">下载(PPT)</dd>
              <dd @click="expImage">下载(JPG)</dd>
            </div>
          </template>
          <a-button type="primary" class="dark" size="large">
            <i class="appIcon-iconfont appIcon-xiazaijiepingmoren"></i>下载
          </a-button>
        </a-popover>

      </div>

      <div class="menu-item" @click="saveDoc()">
        <a-button type="primary" size="large">
          保存
        </a-button>
      </div>
    </div> -->
    <div class="right">
      <!-- 已共享人列表 && 在线人数 -->
      <div class="imglist" v-if="ownerSharerList.length > 0">
        <span class="img-box" v-for="(item, index) in ownerSharerList" :key="index" v-show="index < 5">
          <img :src="item.userAvatar" />
        </span>
        <span class="img-box" v-if="ownerSharerList.length > 5">{{
        ownerSharerList.length
        }}</span>
        <div class="online-user">
          上线<font>{{ handleElementOtherIdList.length }}</font>
        </div>
      </div>

      <Tooltip class="handler-item icon" :mouseLeaveDelay="0" :mouseEnterDelay="0.5" title="emi纸飞机">
        <i class="appIcon-iconfont appIcon-emizhifeiji fz14" @click="fare()"></i>
      </Tooltip>

      <a-popover placement="bottom" trigger="click" overlayClassName="downloadAs">
        <template #content v-if="EditorType!=1">
          <div class="downloadFlex">
            <dd @click="exportPPTX">下载(PPT)</dd>
            <dd @click="expImage">下载(JPG)</dd>
            <!-- <dd>下载(PDF)</dd> -->
          </div>
        </template>

        <Tooltip class="handler-item icon" :mouseLeaveDelay="0" :mouseEnterDelay="0.5" title="下载">
          <i class="appIcon-iconfont appIcon-xiazai fz14" @click="EditorType==1?expImage():''"></i>
        </Tooltip>

      </a-popover>

      <a-popover placement="bottom" trigger="click" overlayClassName="downloadAs">
        <template #content v-if="EditorType!=1">
          <div class="downloadFlex">
            <dd @click="autoplay">自动播放</dd>
            <dd @click="enterScreeningFromStart()">手动播放</dd>
          </div>
        </template>
        <Tooltip class="handler-item icon" :mouseLeaveDelay="0" :mouseEnterDelay="0.5" title="播放">
          <i class="appIcon-iconfont appIcon-bofang1 fz14" @click="EditorType==1?enterScreeningFromStart():''"></i>
        </Tooltip>
      </a-popover>
    </div>

    <div class="export-img">
      <div class="thumbnails-view">
        <div class="thumbnails" ref="imageThumbnailsRef">
          <ThumbnailSlide class="thumbnail" v-for="slide in slides" :key="slide.id" :slide="slide" :size="1000" />
        </div>
      </div>
    </div>
    <a-modal v-model:visible="visible" class="faremodal" :footer="null" width="384px" :closable="false" centered>
      <div class="modal">
        <div class="share-tile">分享链接</div>
        <div class="flex">
          <div class="share-url">{{ fareurl }}</div>
          <!-- <a-input v-model:value="fareurl" size="large" /> -->

          <a-button @click="copyUrl" class="copy-btn" type="primary" v-if="copyState == '复制'">
            <i class="appIcon-iconfont appIcon-fuzhi fuzhi"></i>
          </a-button>
          <a-button @click="copyUrl" class="copy-btn-done" type="primary" v-if="copyState == '复制成功'">
            <i class="appIcon-iconfont appIcon-fuzhichenggong fuzhidone"></i>
          </a-button>
        </div>
      </div>
    </a-modal>
    <Drawer width="320" placement="right" :visible="hotkeyDrawerVisible" @close="hotkeyDrawerVisible = false">
      <HotkeyDoc />
    </Drawer>
    <Modal v-model:visible="customVisible" class="createmodal" :footer="null" centered :width="404" destroyOnClose>
      <div class="model">
        <div class="model-title">创建组件</div>
        <!-- <p>所选的图层将会生成为一个单独的组件</p> -->
        <div class="flex0">
          <Input :class="{ customNameTest: customNameTest }" v-model:value="customName" @change="customNameTest = false"
            showCount :maxlength="10" placeholder="请输入组件名称" @keyup.enter="createCustom()" />
          <Button @click="createCustom()" :class="{ customBtnTest: !customName }">创建1</Button>
          <div class="type-row">
            <div style="margin-right: 40px" @click="customType = 0">
              <span class="type-label">私有组件</span>
              <i :class="[
                'appIcon-iconfont',
                customType == 0
                  ? 'appIcon-xuanzechengyuan'
                  : 'appIcon-weixuanbeifen',
              ]" :style="{ color: customType == 0 ? '#686CE8' : '#92A1B7' }"></i>
            </div>
            <div @click="customType = 1">
              <span class="type-label">公开组件</span>
              <i :class="[
                'appIcon-iconfont',
                customType == 1
                  ? 'appIcon-xuanzechengyuan'
                  : 'appIcon-weixuanbeifen',
              ]" :style="{ color: customType == 1 ? '#686CE8' : '#92A1B7' }"></i>
            </div>
          </div>
          <!-- <a-radio-group v-model:value="customType">
            <a-radio :value="0">
              私有组件
            </a-radio>
            <a-radio :value="1">
              公开组件
            </a-radio>
          </a-radio-group> -->
        </div>
      </div>
    </Modal>
    <FullscreenSpin :loading="exporting" tip="正在导出..." />
    <FullscreenSpin :loading="saveing" tip="正在保存..." />
    <FullscreenSpin :loading="getoneing" tip="正在加载..." />
    <div class="thumbnailsMin">
      <ThumbnailSlide class="thumbnailMin" :slide="slides[0]" :size="1000" />
    </div>
  </div>
</template>

<script lang="ts">
import {
  computed,
  defineComponent,
  nextTick,
  onBeforeMount,
  onMounted,
  onUnmounted,
  ref,
  watch,
} from "vue";
import { storeToRefs } from "pinia";
import {
  useMainStore,
  useSnapshotStore,
  useScreenStore,
  useSlidesStore,
} from "@/store";
import { editSpaceOffice, getOne, deleteContent, addEditor, editorEditor, getEditor, addUploads, obscapture } from "@/api/content";
import { addCustomTempaleList } from "@/api/custom_template";
import useScreening from "@/hooks/useScreening";
import useSlideHandler from "@/hooks/useSlideHandler";
import useHistorySnapshot from "@/hooks/useHistorySnapshot";
import useExport from "@/hooks/useExport";
import { useRouter, useRoute } from "vue-router";
import HotkeyDoc from "./HotkeyDoc.vue";
import { copyText } from "@/utils/clipboard";
import { PageInformation, PPTElement } from "@/types/slides";
import { message } from "ant-design-vue";
import emitter, { EmitterEvents } from "@/utils/emitter";
import { PROJECTDATA, VIEWPOT } from "@/configs/projectdata";
import html2canvas from "html2canvas";
import { Slide } from "@/types/slides";
// import request from '@/utils/request'
import ThumbnailSlide from "@/views/components/ThumbnailSlide/index.vue";
import { urlToBase64, base64ToUrl } from "@/utils/image";
import useAlignElementToCanvas from "@/hooks/useAlignElementToCanvas";
import { ElementOrderCommands, ElementAlignCommands } from "@/types/edit";
import useUniformDisplayElement from "@/hooks/useUniformDisplayElement";
import useCombineElement from "@/hooks/useCombineElement";
import useCopyAndPasteElement from "@/hooks/useCopyAndPasteElement";
import useOrderElement from "@/hooks/useOrderElement";
import useLockElement from "@/hooks/useLockElement";
import { ImageOrShapeFlip } from "@/types/slides";
import { ENV } from "@/configs/env"
import { initWebSocket, sendData, closewebsocket } from "@/utils/webScoket";

export default defineComponent({
  name: "editor-header",
  components: {
    HotkeyDoc,
    ThumbnailSlide,
  },
  setup() {
    const copyState = ref("复制");
    const mainStore = useMainStore();
    const screenStore = useScreenStore();
    const router = useRouter();
    const route = useRoute();
    const {
      showGridLines,
      customList,
      activeGroupElementId,
      activeElementIdList,
      activeElementList,
      pptTitle,
      indexImage,
      handleElementId,
      handleElement,
      handleElementOtherIdList, // 协同在线人数
      EditorType,  //编辑器类型
    } = storeToRefs(mainStore);
    const { renderdata } = storeToRefs(screenStore);
    const checked = ref<boolean>(false); // 按钮
    const { alignElementToCanvas } = useAlignElementToCanvas();
    const {
      displayItemCount,
      uniformHorizontalDisplay,
      uniformVerticalDisplay,
    } = useUniformDisplayElement();
    const { canCombine, combineElements, uncombineElements } =
      useCombineElement();
    const { copyElement, pasteElement, cutElement } = useCopyAndPasteElement();
    const { orderElement }: any = useOrderElement();
    const { lockElement, unlockElement }: any = useLockElement();

    const visible = ref<boolean>(false);

    const layerVisible = ref<boolean>(false); // 图层click是否显示
    const alignmentVisible = ref<boolean>(false); // 对齐方式click是否显示

    const customVisible = ref<boolean>(false);

    const title = ref<string>("未命名文件");
    const fareurl = ref<string>(
      `https:///?oparate=2&appFileInfoId=${route.query.appFileInfoId}&screen=1`
    );
    const slidesStore = useSlidesStore();
    const { slides, viewportRatio, theme } = storeToRefs(slidesStore);
    const pageInfo = ref<any>();
    const suoType = ref<Boolean>(false);

    const { enterScreening, enterScreeningFromStart } = useScreening();
    const { createSlide, deleteSlide, resetSlides } = useSlideHandler();
    const { redo, undo, addHistorySnapshot } = useHistorySnapshot();
    const { exporting, exportJSON, exportPPTX, exportImage, htmlToImage } =
      useExport();
    const { canUndo, canRedo } = storeToRefs(useSnapshotStore());
    const customName = ref();
    const customNameTest = ref(false);
    const customType = ref(0);
    const toggleGridLines = () => {
      mainStore.setGridLinesState(!showGridLines.value);
    };
    const imageThumbnailsRef = ref<HTMLElement>();
    const format = ref<"jpeg" | "png">("jpeg");
    const quality = ref(1);
    const ignoreWebfont = ref(false);
    const hideElement = (bool: boolean) => {
      updateHideOrShow({ hide: bool });
    };
    const updateHideOrShow = (props: any) => {
      if (!handleElement.value) return;
      slidesStore.updateElement({ id: handleElement.value.id, props });
      // addHistorySnapshot()
    };
    const flipH = ref(false);
    const flipV = ref(false);
    watch(
      handleElement,
      () => {
        if (
          handleElement.value &&
          (handleElement.value.type === "image" ||
            handleElement.value.type === "shape")
        ) {
          flipH.value = !!handleElement.value.flipH;
          flipV.value = !!handleElement.value.flipV;
        }
      },
      { deep: true, immediate: true }
    );
    const updateFlip = (flipProps: ImageOrShapeFlip) => {
      if (!handleElement.value) return;
      slidesStore.updateElement({
        id: handleElement.value.id,
        props: flipProps,
      });
      addHistorySnapshot();
    };
    const expImage = async () => {
      // console.log(imageThumbnailsRef.value, 'imageThumbnailsRef')
      let parentDom = document.querySelector(
        ".thumbnailMin"
      ) as HTMLElement;
      let imgList = parentDom.querySelectorAll("img");
      for (let i = 0; i < imgList.length; i++) {
        const url: any = imgList[i].getAttribute("src");
        if (url.startsWith("http")) {
          await urlToBase64(url ? url : "").then((res) => {
            imgList[i].setAttribute("src", res);
          });
        }
      }
      // console.log(parentDom, 'parentDom')
      nextTick(() => {
        if (!imageThumbnailsRef.value) return;
        exportImage(
          parentDom,
          format.value,
          quality.value,
          ignoreWebfont.value
        );
      });
    };
    const replaceDomImageSrc = (dom: HTMLElement) => {
      // console.log(dom)
    };
    const hotkeyDrawerVisible = ref(false);
    const leave = ref(false);
    const goback = () => {
      leave.value = true;
      saveDoc();
      // saveing.value === false ? router.go(-1) : ''
    };

    // 获取共享人员列表
    let ownerSharerList: any = [];
    if (localStorage.getItem("ownerSharerList")) {
      let arrString: any = localStorage.getItem("ownerSharerList");
      ownerSharerList = JSON.parse(arrString);
    }

    // 点击锁的事件
    const suoFn = (type: boolean) => {
      console.log("点击锁的事件", type);
      suoType.value = type;
    };
    // 图层点击显示弹窗
    const layerVisibleFn = () => {
      if (handleElementId && activeElementIdList.value.length == 1) {
        layerVisible.value = !layerVisible.value;
        alignmentVisible.value = false;
      } else {
        layerVisible.value = false;
      }
    };
    // 对齐方式点击显示弹窗
    const alignmentVisibleFn = () => {
      if (handleElementId && activeElementIdList.value.length == 1) {
        alignmentVisible.value = !alignmentVisible.value;
        layerVisible.value = false;
      } else {
        alignmentVisible.value = false;
      }
    };
    // 监听是否选取到元素
    watch(
      () => activeElementIdList.value.length,
      (val) => {
        if (val == 0) {
          layerVisible.value = false;
          alignmentVisible.value = false;
        }
      }
    );
    watch(
      () => suoType.value,
      (val) => {
        val ? lockElement() : "";
      }
    );
    const farebool = ref(false);
    const fare = () => {
      farebool.value = true;
      saveDoc();
      visible.value = true;
      copyState.value = "复制";
    };
    watch(
      () => visible.value,
      (val) => {
        if (!val) farebool.value = false;
      }
    );
    const getPageInfo = () => {
      getOne({ officeId: route.query.wid }).then((res) => {
        if (res.data.code === 200) {
          pageInfo.value = res.data.data;
        }
      });
    };
    const getoneing: any = ref(false);
    const oldSlides = ref();
    const oldViewportRatio = ref();
    const oldTitle = ref();
    const getInfo = () => {
      getoneing.value = true;
      getEditor(route.query.appFileInfoId).then((res) => {
        console.log(res,'geteditor')
        pptid.value = route.query.appFileInfoId
        getoneing.value = false;
        if (res.code === 200) {
          const name = res.data.fileName.split('.')
          // name.slice(0, name.lastIndexOf(".")), 
          title.value = name.slice(0, name.lastIndexOf(".")).join('.');
          mainStore.setTitle(res.data.fileName);
          const currentSlides =JSON.parse(JSON.stringify(res.data.content));
          oldSlides.value = res.data.content;
          oldTitle.value = res.data.fileName;
          slidesStore.setSlides(currentSlides);
         
          if (route.query.screen === "1" || route.query.operate === '3') {
            enterScreening();
          }
        }
      });
    };

    const setSlidesUrl = () => {
      //处理slides里的图片改为url
      slides.value.map((item: any, index: any) => {
        item.elements.map((j: any, i: any, arr: any) => {
          if (j.type === "image" && !j.src.startsWith("http")) {
            base64ToUrl(j.src).then((res) => {
              arr[i].src = res;
            });
          }
        });
      });
      return new Promise((resolve) => {
        resolve(slides.value);
      });
    };

    const saveing = ref(false);
    const saveDoc = async () => {
      let empty: any = slides.value.every((item: any) => {
        return item.elements.length == 0;
      });
      if (empty) {
        //判断是否为空页面
        if (leave.value) {
          //如果是返回按钮
          let params = {
            officeId: route.query.wid,
          };
          if(route.query.fileType) {
            window.parent.postMessage(route.query.operate, "*");
          } else {
            router.go(-1);
          }
          // deleteContent(params).then((res: any) => {
          //   router.back();
          // });
        } else {
          message.info("页面未添加元素！");
        }
        return;
      }
      if (
        oldSlides.value == JSON.stringify(slides.value) &&
        oldTitle.value == title.value &&
        oldViewportRatio.value == mainStore.canvasHeight / mainStore.canvasWidth
      ) {
        //判断页面是否未更改
        leave.value === true
          ? router.back()
          : farebool.value
          ? ""
          : message.info("页面未更改！");
        return;
      }
      const operate: any = route.query.operate
      
      // !farebool.value ? (saveing.value = true) : "";
      slidesStore.setViewportRatio(
        mainStore.canvasHeight / mainStore.canvasWidth
      );
      let bool =
        viewportRatio.value === (3.14 || 1.42 || 0.56 || 0.53 || 1.0 || 2.16);
      let list: any = document.querySelector(".thumbnailMin");

      let newdom = list.querySelectorAll("img");

      for (let i = 0; i < newdom.length; i++) {
        const url = newdom[i].getAttribute("src");
        if (url.startsWith("http")) {
          await urlToBase64(url).then((res) => {
            newdom[i].setAttribute("src", res);
          });
        }
      }
      await htmlToImage(list, "jpeg", 2, true).then((res) => {
        base64ToUrl(indexImage.value).then((res) => {
          if(operate && operate == 1) { //新建
            createContent(res)
            return
          }
          let obj = {
            // // officeFileType: 2,
            // officeBgColor: slides.value[0].background?.color,
            // bgImage: "",
            // officeContent: JSON.stringify(slides.value),
            // officeId: pageInfo.value?.officeId,
            // officeThumbnailContent: res,
            // // imageUrl: canvas.toDataURL("image/png"),
            // officeTitle: title.value,
            // officePercent: 100,
            // officeHeight: bool
            //   ? VIEWPOT[viewportRatio.value].height
            //   : Number(mainStore.canvasHeight.toFixed(2)),
            // officeWidth: bool
            //   ? VIEWPOT[viewportRatio.value].width
            //   : Number(mainStore.canvasWidth.toFixed(2)),
            // // theme.value
            // // viewportRatio.value
            // https:///freeeditor/#/freeeditor?appFileInfoId=361075428040773&screen=1
            fileUrl: `${ENV}/freeeditor/#/freeeditor?appFileInfoId=${pptid.value}&hhxsFolderId=${route.query.hhxsFolderId}&relyOn=${route.query.appFileInfoId}&hhxsUserId=&fileType=11&screen=1`,
            appFileInfoId: pptid.value,
            fileAvatar: res,
            fileType: 11,
            officeFileContent: JSON.stringify(slides.value),
            officeFlag: 1,
            fileName: title.value+'.flse',
          };

          
          editorEditor(obj).then((res: any) => {
            // slidesStore.setSlides({})
            saveing.value = false;
            if (res.data.code === 200) {
              !farebool.value ? message.success("保存成功！") : "";
              pptInfo.value = res.data.data
              // leave.value === true ? router.go(-1) : "";
              uploadFiles()
            }
          });
        });
      });
    };
    const copyUrl = () => {
      copyText(fareurl.value).then((res: any) => {
        // console.log(fareurl, res)
        copyState.value = "复制成功";
      });
    };
    const { currentSlide } = storeToRefs(slidesStore);
    const addcustom = () => {
      if (!groupVisible.value) {
        return;
      }
      if (handleElementId.value === "") {
        message.info("请选择要添加的组件");
        return;
      }
      customVisible.value = true;
      customName.value = "";
    };
    const groupVisible = ref(false);

    watch(
      () => activeElementList.value,
      (val) => {
        let data = JSON.parse(JSON.stringify(val))[0];
        if (val.length > 0) {
          Object.keys(data).includes("groupId")
            ? (groupVisible.value = true)
            : (groupVisible.value = false);
        } else {
          groupVisible.value = false;
        }
      }
    );
    const createCustom = () => {
      if (!customName.value) {
        customNameTest.value = true;
        return;
      }
      const newElementList: PPTElement[] = JSON.parse(
        JSON.stringify(currentSlide.value.elements)
      );
      //  activeElementIdList
      const currentGroupId = newElementList.filter((item) => {
        return item.id === handleElementId.value;
      });
      if (!currentGroupId[0].groupId) {
        message.info("请选择组合元素！");
        return;
      }
      const arr = newElementList.filter((item) => {
        return item.groupId === currentGroupId[0].groupId;
      });

      addCustomTempaleList({
        compContent: JSON.stringify(arr),
        compName: customName.value,
        compType: customType.value,
      }).then((res: any) => {
        if (res.data.code === 200) {
          customVisible.value = false;
          customName.value = "";
          customType.value = 0;
          emitter.emit(EmitterEvents.GET_CUSTOM_LIST, { type: 0 });
          message.success("保存成功！");
        }
      });
      // request.post(`/hhxs-app/app/ssc/comp/save`, {
      //   compContent: JSON.stringify(arr),
      //   compName: customName.value,
      //   compType: customType.value
      // }).then(res => {
      //   if (res.data.code === 200) {
      //     customVisible.value = false
      //     customName.value = ''
      //     customType.value = 0
      //     emitter.emit(EmitterEvents.GET_CUSTOM_LIST, { type: 0 })
      //     message.success('保存成功！')
      //   }
      // })
      // console.log(currentGroupId, '--', 'saveCustom', arr)
    };
    // 点击名字重命名
    const npmeInp = ref<any>(null); // 判断是否点击重命名
    const textFocus = (item: any) => {
      // console.log(item, "item");
      npmeInp.value = "inpname_type_";
      nextTick(() => {
        document.getElementById("inpname_type_")?.focus();
        // morevisible.value = false
      });
    };
    // 失焦事件
    const textblur = () => {
      npmeInp.value = null;
    };
    onBeforeMount(() => {
      if (route.query.screen === "1") {
        enterScreening();
      }
    });
    const autoplay = () => {
      screenStore.setAutoplay(true);
      enterScreeningFromStart();
    };
    const createContent = (url: any) => {
      const snowId = require("simple-flakeid");
      let fileSnowId = 0;
      let gen1 = new snowId.SnowflakeIdv1({
        workerId: 1,
      });
      fileSnowId = gen1.NextId();
      const params = {
        "appFileInfoId": fileSnowId,
        "appFileProperty": {
          "appFileFormat": "flse",
          "appFileSize": 0,
        },
        fileUrl: `${ENV}/freeeditor/#/freeeditor?appFileInfoId=${fileSnowId}&hhxsFolderId=${route.query.hhxsFolderId}&relyOn=${route.query.appFileInfoId}&hhxsUserId=&fileType=11&screen=1`,
        "fileAvatar": url,
        "fileName": title.value+'.flse',
        "fileType": 11,
        officeFileContent: JSON.stringify(slides.value),
        officeFlag: 1,
        "hhxsUserId": userId.value,
        "uploadUserId": userId.value,
        hhxsFolderId: route.query.hhxsFolderId
      };
      addEditor(params).then((res: any) => {
        const pId = res.data.data;
        if (pId) {
          pptid.value = pId.appFileInfoId
          pptInfo.value = res.data.data
          saveing.value = false
          uploadFiles()
        }
      });
    };
    const uploadFiles = () => {
      const arr: any = []
      const slidesarr: any = JSON.parse(JSON.stringify(slides.value)) 
      const snowId = require("simple-flakeid");
      let fileSnowId = 0;
      let gen1 = new snowId.SnowflakeIdv1({
        workerId: 1,
      });
      slidesarr[0].elements.map((item: any) => {
        if(item.type == 'image' || item.type == 'video') {
          const filename = item.src.split('?')[0].split('/')
          const name = filename[filename.length-1]
          if(item.type == 'video') {  //如果是视频 则截取封面图
            const src = item.src.split('.com/')[1].split('/')
            const obj = {
              dots: [1],
              inputObject: item.src.split('.com/')[1].split('?')[0],
              outputObject: src.slice(0,3).join('/'),
              outputFileName: name.slice(0, name.lastIndexOf(".")), 
            }
            obscapture(obj).then(res => {
              console.log(res,'obscapture')
            })
          }
          fileSnowId = gen1.NextId();
          let videoUrl = item.src
          const obj = 
          {
            appFileInfoId: fileSnowId,        
            hhxsUserId: route.query.hhxsUserId ? route.query.hhxsUserId : userId.value,   // 共享的url获取，其他自己的     
            uploadUserId: userId.value,   //   
            fileType: item.type == 'image' ? 1 : 2,        
            fileName: filename[filename.length-1],        
            fileUrl: item.src,
            fileAvatar: item.type=='video' ? videoUrl.slice(0, videoUrl.lastIndexOf(".")) + ".jpg" : videoUrl,
            relyOn: pptInfo.value.appFileInfoId,     
            "appFileProperty": {
                "appFileFormat": filename[filename.length-1].split('.')[1],     
                "appFileSize": 0,
            },
          }
          arr.push(obj)
        }
      })
      addUploads({
        parentAppFileInfoId: pptid.value,
        appFileInfos: arr
      }).then(res => {
        console.log(res,'addUploads',route.query)
        // router.go(-1)
        if(farebool.value) return
        if(route.query.fileType) {
          window.parent.postMessage(route.query.operate, "*");
        } else {
          router.go(-1);
        }
      })
    }
    const pptid = ref()
    const pptInfo = ref()
    const userId = ref()
    onMounted(() => {
      // hhxsUserId
      //判断云盘进入编辑器，然后操作 operate == 1新建 ==2 编辑 ==3 预览  appFileInfoId 项目id
      const operate: any = route.query.operate
      if(operate == 2 || operate == 1) {
        const userInfo: any = localStorage.getItem('userInfo')
        userId.value = JSON.parse(userInfo).hhxsUserId
      }
      if(operate && (operate == 2 || operate == 3) && renderdata.value) { //编辑
        getInfo()
      }
      //
      console.log(navigator.userAgent, "navigator");
      fareurl.value =
        window.location.origin +
        `/freeeditor/#/freeeditor?oparate=2&appFileInfoId=${route.query.appFileInfoId}&screen=1`;
      // getPageInfo();
      // if (route.query.wid && renderdata.value) {
      //   getInfo();
      // }
      emitter.on(EmitterEvents.SAVE_PROJECT, saveDoc);
      emitter.on(EmitterEvents.CREATE_CUSTOM, addcustom);
      // if (!renderdata.value) {
      //   title.value = pptTitle.value;
      // }
    });
    watch(
      () => title.value,
      (val) => {
        mainStore.setTitle(val);
      }
    );
    onUnmounted(() => {
      emitter.off(EmitterEvents.SAVE_PROJECT, saveDoc);
      emitter.off(EmitterEvents.CREATE_CUSTOM, addcustom);
      // leave.value = false;
      // localStorage.removeItem("ownerSharerList");
    });

    return {
      redo,
      undo,
      showGridLines,
      activeGroupElementId,
      activeElementIdList,
      renderdata,
      hotkeyDrawerVisible,
      exporting,
      enterScreening,
      enterScreeningFromStart,
      createSlide,
      deleteSlide,
      toggleGridLines,
      resetSlides,
      exportJSON,
      exportPPTX,
      expImage,
      canUndo,
      canRedo,
      goback,
      visible,
      fareurl,
      copyUrl,
      fare,
      saveDoc,
      title,
      slides,
      getInfo,
      pageInfo,
      addcustom,
      customName,
      customNameTest,
      customType,
      createCustom,
      customVisible,
      copyState,
      imageThumbnailsRef,
      saveing,
      handleElementId,
      handleElement,
      leave,
      groupVisible,
      activeElementList,
      getPageInfo,
      textFocus,
      npmeInp,
      textblur,
      oldSlides,
      oldViewportRatio,
      oldTitle,
      farebool,
      htmlToImage,
      setSlidesUrl,
      base64ToUrl,
      autoplay,
      checked,
      suoFn,
      suoType,
      alignElementToCanvas,
      canCombine,
      displayItemCount,
      combineElements,
      uncombineElements,
      uniformHorizontalDisplay,
      uniformVerticalDisplay,
      copyElement,
      orderElement,
      lockElement,
      unlockElement,
      updateHideOrShow,
      hideElement,
      updateFlip,
      flipH,
      flipV,
      layerVisibleFn,
      layerVisible,
      alignmentVisibleFn,
      alignmentVisible,
      getoneing,
      ownerSharerList,
      handleElementOtherIdList,
      EditorType
    };
  },
});
</script>
<style lang="scss">
.input-title {
  background: none;
  font-size: 16px;
  padding: 0;
  line-height: 36px;
  width: 120px;
  text-align: center;
}

.faremodal {
  .ant-modal-content {
    background: #1e2330;
    border-radius: 10px;
  }
}

.createmodal {
  .ant-modal-content {
    background: white;
    border-radius: 10px;
  }
}
</style>
<style lang="scss" scoped>
.cursornodrop {
  cursor: no-drop;
}

.share-tile {
  margin-bottom: 20px;
  font-size: 18px;
  color: #ffffff;
  letter-spacing: 0;
  line-height: 16px;
  font-weight: 400;
}

.share-url {
  padding-left: 16px;
  height: 50px;
  background: #1e2330;
  border: 1px solid #515151;
  border-radius: 10px;
  font-size: 18px;
  color: #ffffff;
  letter-spacing: 0;
  line-height: 50px;
  font-weight: 400;
  @include ellipsis-oneline();
}

.copy-btn {
  width: 50px;
  height: 50px !important;
  background: #4355dc !important;
  border-radius: 10px;

  &:hover {
    color: #fff;
  }

  i {
    font-size: 21px;
  }
}

.copy-btn-done {
  width: 50px;
  height: 50px !important;
  background: #4355dc;
  border-radius: 10px;

  &:hover {
    color: #fff;
  }

  i {
    font-size: 15px;
  }
}

.export-img {
  height: 500px;
  bottom: 0;
  right: 0;
  display: flex;
  justify-content: center;
  position: fixed;
  overflow: hidden;
}

.thumbnailsMin {
  position: absolute;
  z-index: -1;
  right: 30px;
  bottom: 30px;
}

.thumbnails-view {
  position: absolute;
  // top: 0;
  // bottom: 0;
  // left: 0;
  // right: 0;

  &::after {
    content: "";
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    background-color: #fff;
  }
}

.modal {
  .flex0 {
    position: relative;
  }

  h2 {
    font-size: 16px;
    font-weight: 500;
  }

  input {
    width: 100%;
    height: 46px;
    line-height: 46px;
    background: #f8f9fa;
    color: #9da9c6;
    border-radius: 10px;
  }

  .ant-btn {
    // background: #686ce8 !important;
    height: 50px;
    border-radius: 10px;
    display: flex;
    justify-content: center;
    align-items: center;
    position: absolute;
    right: 0;
    top: 0;
  }
}

.model {
  .flex0 {
    position: relative;

    .ant-radio-group {
      margin-top: 20px;
    }
  }

  h3 {
    font-weight: 600;
    font-size: 16px;
  }

  p {
    color: #959fba;
    font-size: 14px;
    line-height: 14px;
    margin: 15px 0;
  }

  input {
    height: 46px;
    background: #f8f9fa;
    border-radius: 10px;
    border: 1px solid rgba(240, 241, 243, 1);
  }

  .customNameTest {
    border: 1px solid red;
  }

  .customBtnTest {
    opacity: 0.5;
  }

  button {
    position: absolute;
    right: 0;
    height: 46px;
    width: 80px;
    border-radius: 10px;
    background: #686ce8;
    font-size: 16px;
    color: #ffffff;
    letter-spacing: 0;
    // line-height: 46px;
    font-weight: 400;

    &:hover,
    &:active,
    &:focus {
      background: #7a7ef0 !important;
      color: #fff;
    }
  }
}

.editor-header {
  background-color: $topbarGray;
  user-select: none;
  border-bottom: 1px solid $borderColor;
  display: flex;
  justify-content: space-between;
  padding: 0 10px;
  height: 37px;
  .icon {
    border: 1px solid rgba(85, 234, 177, 0.3);
  }
}

.left {
  margin-left: 20px;

  // .undo {
  //   transform: rotateY(180deg);
  // }

  .handler-item {
    display: block;
    height: 32px;
    padding: 0 5px;
    text-align: center;
    margin-right: 26px;
    color: rgba(85, 234, 177, 1);
    text-align: center;
    line-height: 32px;
    // background: $leftbg;
    border-radius: 8px;
    cursor: pointer;
    font-size: 20px;

    i {
      font-size: 20px;
    }
  }

  .icon-chuangjianzujian {
    font-size: 18px;

    &.disable {
      cursor: no-drop;
    }
  }

  .disable::before {
    opacity: 0.6;
  }
}

.center {
  &:hover .inp_icon {
    display: inline-block;
  }

  input {
    text-align: center;
    background: none;
    color: #fff;
    width: 170px;
    height: 30px;
    font-size: 18px;
    border-bottom: 1px dashed #fff;
  }

  .inp_icon {
    color: #fff;
    display: none;
  }

  .inp_span {
    color: #fff;
    font-size: 18px;
  }

  .handler-item {
    display: block;
    width: 42px;
    height: 42px;
    margin-right: 26px;
    color: #fff;
    text-align: center;
    line-height: 42px;
    // background: $leftbg;
    border-radius: 8px;
    font-size: 16px;

    &:hover {
      color: #fff !important;
    }
  }
}

.right {
  .handler-item {
    display: block;
    width: 32px;
    height: 32px;
    margin-right: 26px;
    color: rgba(85, 234, 177, 1);
    text-align: center;
    line-height: 32px;
    // background: $leftbg;
    border-radius: 8px;
  }
}

.left,
.right,
.center {
  display: flex;
  justify-content: center;
  align-items: center;
}

.menu-item {
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 14px;
  margin-right: 26px;
  transition: all $transitionDelay;
  cursor: pointer;

  &:hover {
    >.appIcon-iconfont {
      transition: all $transitionDelay;
      font-size: 20px;
    }
  }

  .icon-xiazaijiepingmoren {
    margin-right: 10px;
  }

  .ant-btn {
    padding: 0 30px;
    border-radius: 8px;
    border: 0;
    height: 42px;
    line-height: 42px;
  }

  .ant-btn-primary {
    background: $buttonPrimary;
  }

  .dark {
    background: $leftbg;
  }

  .text {
    margin-left: 4px;
  }
}

.left .menu-item:hover {
  background-color: $lightGray;
}

.handler-item,
.menu-item {
  transition: 0.5s all ease;
}

.create-model {
  background: #ffffff;
  border-radius: 10px;
}

.model-title {
  margin-bottom: 20px;
  font-size: 18px;
  color: #4b4d54;
  letter-spacing: 0;
  line-height: 16px;
  font-weight: 400;
}

.type-row {
  margin-top: 26px;
  display: flex;

  .type-label {
    margin-right: 12px;
    font-size: 16px;
    color: #6c6c84;
    letter-spacing: 0;
    line-height: 16px;
    font-weight: 400;
    cursor: pointer;
  }

  i {
    width: 20px;
    height: 20px;
    transition: all 0.3s;
  }

  i:hover {
    color: #9598fb;
  }
}

.editor_top_line {
  width: 1px;
  height: 10px;
  border: solid 1px #1e2127;
  margin: 0 13px 0 -13px;
}

.icon_route90 {
  display: inline-block;
  transform: rotateZ(-90deg);
}

.icon_route-90 {
  display: inline-block;
  transform: rotateZ(90deg);
}

.icon_route180 {
  display: inline-block;
  transform: rotateZ(-180deg);
}

.c_bbbdc4 {
  color: #bbbdc4 !important;
}

.fz16 {
  font-size: 16px;
}

.fz14 {
  font-size: 14px;
}

// 在线人员列表
.imglist {
  display: flex;
  align-items: center;
  line-height: 30px;
  padding: 0 0 0 60px;
  font-size: 12px;
  // position: fixed;
  right: -20px;
  top: 0;
  transform: scale(0.7);

  span.img-box {
    display: inline-block;
    text-align: center;
    vertical-align: top;
    width: 30px;
    height: 30px;
    line-height: 26px;
    border: 2px solid #fff;
    border-radius: 50%;
    overflow: hidden;
    background: #f1f2ff;
    margin-left: -12px;
    color: #7a8bbf;
  }

  .online-user {
    padding: 0 10px;
    height: 34px;
    line-height: 34px;
    background: #5ce6cd;
    box-shadow: 0px 4px 5px 0px rgba(122, 132, 255, 0.12);
    border-radius: 10px;
    font-size: 16px;
    color: #ffffff;
    margin-left: 25px;

    font {
      text-align: center;
      display: inline-block;
      padding: 0 5px;
      box-sizing: border-box;
      min-width: 26px;
      height: 26px;
      line-height: 26px;
      background: rgba(255, 255, 255, 0.3);
      border-radius: 8px;
      margin-left: 6px;
    }
  }

  img {
    width: 100%;
    height: 100%;
  }
}
</style>
